#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<vector>
#include<string>

const int N = 15;
int n, m;
bool vis[N][N];
int dx[8] = { 0,0,1,-1,-1,-1,1,1 };
int dy[8] = { 1,-1,0,0,-1,1,-1,1 };
char dz[8] = { '2','6','4','0','7','1','5','3' };
vector<string> ret;
string path;

void dfs(vector<vector<int>>& a, int i, int j)
{
	int val = a[i][j];
	if (i == n && j == n)
	{
		ret.push_back(path);
		return;
	}
	for (int k = 0; k < 8; k++)
	{
		int x = dx[k] + i, y = dy[k] + j;
		if (x >= 1 && x <= n && y >= 1 && y <= n && !vis[x][y] && (a[x][y] == val + 1 || (val == k - 1 && a[x][y] == 0)))
		{
			vis[x][y] = true;
			path.push_back(dz[k]);
			dfs(a, x, y);
			vis[x][y] = false;
			path.pop_back();
		}
	}
}

int main()
{
	std::ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m;
	vector<vector<int>> a(n + 1, vector<int>(n + 1));
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			cin >> a[i][j];
		}
	}
	vis[1][1] = true;
	dfs(a, 1, 1);
	if (ret.size())
		cout << ret[0] << endl;
	else
		cout << -1 << endl;
	return 0;
}

